<?php
/**
 * 自定义表单
 *
 * @package         YDCMS
 * @author          QQ:644157559 <644157559@qq.com>
 * @version         $Id: DiyFormController.class.php v1.0 2014-06-12 17:27:03 $
 */
namespace Admin\Controller;
class DiyFormController extends CommonController{
    private $model;
    private $service;
    public function _initialize() {
        parent::_initialize();
        $this->model = D("DiyForm");
        $this->service = D("DiyForm", "Service");
        $fieldtype = D("Field")->fieldtype;
        unset($fieldtype['img']);
        unset($fieldtype['imgfile']);
        $this->fieldtype = $fieldtype;
        $this->assign('fieldtype', $fieldtype);
    }
    
    /**
     * 列表
     */
    public function index() {
        $result = $this->getPagination("DiyForm");
        $this->assign("list", $result['data']);
        $this->assign("count", $result['total_rows']);
        $this->assign("page", $result['show']);
        $this->display();
    }
    
    /**
     * 获取自定义表单前台提交数据
     * @return type
     */
    public function lists() {
        $id = I("get.id", 0, "intval");
        if(empty($id)){
            return $this->errorReturn("无效操作！");
        }
        $diyForms = $this->service->getById($id);
        if(!isArrayAndNotEmpty($diyForms)){
            return $this->errorReturn("无效操作！");
        }
        $result = $this->service->getDiyList($diyForms);
        
        $this->assign("name", $diyForms['formname']);
        $this->assign("diyid", $diyForms['id']);
        $this->assign("fieldlist", unserialize($diyForms['fields']));
        $this->assign($result);
        $this->display();
    }
    
    /**
     * 处理自定义表单前台提交数据
     */
    public function DoDiyData() {
        $act = I("post.act", "");
        if(!in_array($act, array("check", "delete"))){
            return $this->errorReturn("无效操作！");
        }
        $ids = I("post.ids", NULL);
        $diyid = I("post.diyid", 0);
        if(!isArrayAndNotEmpty($ids) || empty($diyid)){
            return $this->errorReturn("无效操作！");
        }
        $diyForms = $this->service->getById($diyid);
        if(!isArrayAndNotEmpty($diyForms)){
            return $this->errorReturn("无效操作！");
        }
        if(isset($diyForms['formtable'])){
            $M = M($diyForms['formtable']);
        }else{
            return $this->errorReturn("无效操作！");
        }
        if($act == "check"){
            $rs = $M->where(array("id" => array("in", $ids)))->setField("ifcheck", 1);
            if($rs === false){
                return $this->errorReturn("审核失败！");
            }
        }else if($act == "delete"){
            $rs = $M->where(array("id" => array("in", $ids)))->delete();
            if($rs === false){
                return $this->errorReturn("删除失败！");
            }
        }
        return $this->successReturn("操作成功！", U("lists", array("id" => $diyid)));
    }
    /**
     * 添加
     */
    public function add() {
        $row = $this->service->getRow(array(), "id desc");
        if(isArrayAndNotEmpty($row)){
             $newdiyid = $row['id']+1;
        }else{
             $newdiyid = 1;
        }
        $this->assign('newdiyid', $newdiyid);
        $this->display();
    }
    
    /**
     * 创建自定义表单
     * @return type
     */
    public function create() {
        $diyForms = I("post.diy", NULL);
        if(!isArrayAndNotEmpty($diyForms)){
            return $this->errorReturn("无效操作！");
        }
        
        if(isset($diyForms['fields'])){
            unset($diyForms['fields']);
        }
        $result = $this->service->add($diyForms);
        if(!$result['status']){
            return $this->errorReturn($result['data']['error']);
        }
        
        return $this->successReturn("添加表单成功！", U("index"));
        
    }
    
    /**
     * 修改自定义表单
     * @return type
     */
    public function edit() {
        $id = I("get.id", 0, "intval");
        if($id <= 0){
            return $this->errorReturn("无效操作！");
        }
        $diyForms = $this->service->getById($id);
        if(!isArrayAndNotEmpty($diyForms)){
            return $this->errorReturn("无效操作！");
        }
        if($diyForms['fields'] != ''){
            $diyForms['fields'] = unserialize($diyForms['fields']);
        }
        $this->assign($diyForms);
        $this->display();
        
    }
    
    /**
     * 更新自定义表单
     * @return type
     */
    public function update() {
        $diyForms = I("post.diy", NULL);
        if(!isArrayAndNotEmpty($diyForms)){
            return $this->errorReturn("无效操作！");
        }
        
        if(isset($diyForms['fields'])){
            unset($diyForms['fields']);
        }
        if(isset($diyForms['formtable'])){
            unset($diyForms['formtable']);
        }
        $result = $this->service->update($diyForms);
        if(!$result['status']){
            return $this->errorReturn($result['data']['error']);
        }
        
        return $this->successReturn("更新表单成功！", U("index"));
    }
    
    /**
     * 删除自定义表单
     * @return type
     */
    public function delete() {
        $id = I("post.id", 0, "intval");
        if($id <= 0){
            return $this->errorReturn("无效操作！");
        }
        $diyForms = $this->service->getById($id);
        if(!isArrayAndNotEmpty($diyForms)){
            return $this->errorReturn("你所指定的自定义表单信息不存在！");
        }
        //删除数据表
        $this->model->dropTable($diyForms['formtable']);
        //删除自定义表单
        if($this->service->delete($id)){
            return $this->successReturn("删除表单成功！", U("index"));
        }else{
            return $this->errorReturn("删除失败！");
        }
    }
    
    /**
     * 添加字段
     * @return type
     */
    public function addfield() {
        $formid = I("get.id", 0, "intval");
        if($formid <= 0){
            return $this->error("无效操作！");
        }
        //判断表单是否存在
        $diyForms = $this->service->getById($formid);
        if(!isArrayAndNotEmpty($diyForms)){
            return $this->error("你所指定的自定义表单信息不存在！");
        }
        //获取表字段
        $fields = M($diyForms['formtable'])->getDbFields();
        
        $f = '';
        foreach($fields as $k=>$v)
        {
            $f .= ($f=='' ? $v : ' '.$v);
        }
        $this->assign('f', $f);
        $this->assign("id", $formid);
        $this->display();
    }
    
    /**
     * 修改字段
     * @return type
     */
    public function editfield() {
        $formid = I("get.id", 0, "intval");
        $fieldname = I("get.fieldname", "");
        if($formid <= 0){
            return $this->error("无效操作！");
        }
        //判断表单是否存在
        $diyForms = $this->service->getById($formid);
        if(!isArrayAndNotEmpty($diyForms)){
            return $this->error("你所指定的自定义表单信息不存在！");
        }
        
        $field_arr = unserialize($diyForms['fields']);
        //判断要修改的字段是否存在数据库
        if(!isset($field_arr[$fieldname])){
            return $this->error("无效操作！");
        }
        $fields = M($diyForms['formtable'])->getDbFields();
        
        $f = '';
        foreach($fields as $k=>$v)
        {
            $f .= ($f=='' ? $v : ' '.$v);
        }
        
        //var_dump($fields, $field_arr);die;
        $this->assign('f', $f);
        $this->assign("id", $formid);
        $this->assign($field_arr[$fieldname]);
        $this->display();
    }
    
    /**
     * 添加字段 add
     * 修改字段 edit
     * 删除字段 delete
     * @return type
     */
    public function doField() {
        $act = I("post.act", "add");//动作
        
        if(!in_array($act, array("add", "edit", "delete"))){
            return $this->errorReturn("无效操作！");
        }
        $formid = I("post.id", 0, "intval");//自定义表单ID
        if($formid <= 0){
            return $this->errorReturn("无效操作！");
        }
        
        //判断表单是否存在
        $diyForms = $this->service->getById($formid);
        if(!isArrayAndNotEmpty($diyForms)){
            return $this->errorReturn("你所指定的自定义表单信息不存在！");
        }
        if($diyForms['fields'] != ''){
            $oldField = unserialize($diyForms['fields']);
        }else{
            $oldField = array();
        }
        $trueTable = C("DB_PREFIX") . $diyForms['formtable'];
        
        //delete start
        if ($act == 'delete'){//删除字段
            $fieldname = I("post.fieldname");
            //判断要删除的字段是否存在
            if(!isset($oldField[$fieldname])){
                return $this->errorReturn("无效操作！");
            }
            unset($oldField[$fieldname]);
            $data = array();
            $data['fields'] = serialize($oldField);
            $data['id'] = $formid;
            $result = $this->service->update($data, 'field');//更新数据
            if(!$result['status']){
                $this->errorReturn($result['data']['error']);
            }
            $this->model->dropColumn($trueTable, $fieldname);//删除字段
            return $this->successReturn("删除字段成功", U("edit", array("id" => $formid)));
        }//end delete
        
        
        //获取修改或添加的字段信息
        $field = I("post.field");
        if(!isArrayAndNotEmpty($field) && isset($field['name'])){
            return $this->errorReturn("无效操作！");
        }
        
        //修改字段配置信息
        $fieldname = strtolower($field['name']);//字段名称
        $dtype = $field['type'];//字段类型
        $comment = $field['comment'];//表单提示文字
        $dfvalue = trim($field['value']);//默认值
        $mxlen = $field['length'];//长度
        
        //检测被修改的字段类型
        $fieldinfos = GetFieldMake($dtype,$fieldname,$dfvalue,$mxlen);
        $ntabsql = $fieldinfos[0];
        $buideType = $fieldinfos[1];
        
        //检查字段是否合法
        if(!$this->model->isFieldName($fieldname)){
            $this->errorReturn("字段不合法！");
        }
        //表不存在在创建表
        if($this->model->checkTable($trueTable)){
            $mysql_version = $this->model->GetVersion();
            //检测数据库是否存在附加表，不存在则新建一个
            $tabsql = "CREATE TABLE IF NOT EXISTS  `$trueTable`(
            `id` int(10) unsigned NOT NULL auto_increment,
            `ifcheck` tinyint(1) NOT NULL default '0',
            `subtime` int(10) NOT NULL default '0',
            ";
            if($mysql_version < 4.1)
            {
                $tabsql .= " PRIMARY KEY  (`id`)\r\n) TYPE=MyISAM; ";
            }
            else
            {
                $tabsql .= " PRIMARY KEY  (`id`)\r\n) ENGINE=MyISAM DEFAULT CHARSET=utf8; ";
            }
            $this->model->execute($tabsql);
        }
        //添加字段
        if($act == 'add'){
            if($this->model->fieldExists($trueTable, $fieldname)){
                $this->errorReturn("字段已存在！");
            }
            //添加字段的sql语句
            $sql = " ALTER TABLE `$trueTable` ADD  $ntabsql ";

            if(false === $this->model->execute($sql)){
                $gerr = $this->model->getError();
                $this->errorReturn("增加字段失败，错误提示为：".$gerr);
            }
            //新字段信息
            $newField[$fieldname] = array(
                'name' => $fieldname,
                'comment' => $comment,
                'type'      => $dtype,
                'length'    => $mxlen,
                'value'     => $dfvalue
            );
            $data = array();
            if(isArrayAndNotEmpty($oldField)){//和以前的字段数据何必并系列化
                $data['fields'] = serialize(array_merge($oldField, $newField));
            }else{
                $data['fields'] = serialize($newField);//系列化字段信息
            }
            $data['id'] = $formid;//表单ID
            $result = $this->service->update($data, 'field');//更新
            if(!$result['status']){//判断
                $this->model->dropColumn($trueTable, $fieldname);//失败删除已创建的字段
                $this->errorReturn($result['data']['error']);
            }
            //成功
            return $this->successReturn("添加字段成功", U("edit", array("id" => $formid)));
        }//添加字段结束
        //修改字段
        else if ($act == 'edit') {
            //检测表里含有的字段
            $fields = array();
            $res = $this->model->query("show fields from `$trueTable`");
            foreach ($res as $val) {
                $fields[ strtolower($val['Field']) ] = $val['Type'];
            }
            
            foreach ($oldField as $key => $val) {
                if($key == trim($fieldname)){//判断字段是否存在自定义表单数据里面
                    if(isset($fields[$fieldname]) && $fields[$fieldname] != $buideType){//存在并改变了字段类型，修改字段
                        $tabsql = "ALTER TABLE `$trueTable` CHANGE `$fieldname` ".$ntabsql;
                        $rs = $this->model->execute($tabsql);
                    } else if(!isset($fields[$fieldname])){//存在但是不存在数据表里面，创建字段
                        $tabsql = "ALTER TABLE `$trueTable` ADD ".$ntabsql;
                        $rs = $this->model->execute($tabsql);
                    } else {
                        $tabsql = '';
                    }
                    break;
                }
            }
            if(false === $rs && $tabsql != ""){
                $this->errorReturn("出错了！");
            }
            //字段新信息
            $newField[$fieldname] = array(
                'name' => $fieldname,
                'comment' => $comment,
                'type'      => $dtype,
                'length'    => $mxlen,
                'value'     => $dfvalue
            );
            $data = array();
            if(isArrayAndNotEmpty($oldField)){
                $data['fields'] = serialize(array_merge($oldField, $newField));//合并字段并系列化
            }else{
                $data['fields'] = serialize($newField);//系列化字段信息
            }
            $data['id'] = $formid;
            $result = $this->service->update($data, 'field');//更新
            if(!$result['status']){
                $this->errorReturn($result['data']['error']);
            }
            //成功
            return $this->successReturn("修改字段成功", U("edit", array("id" => $formid)));
        }//修改字段结束
        
        else{
            $this->errorReturn("无效操作！");
        }
    }
}
